package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @PostMapping
    public Result<String> save(@RequestBody Category category, HttpServletRequest request){

        categoryService.save(category);

        return Result.success("添加成功");
    }

    @GetMapping("/page")
    public  Result getByPage(Integer page ,Integer pageSize){

        Page<Category> categoryPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);

        categoryPage = categoryService.page(categoryPage,wrapper);

        return Result.success(categoryPage);
    }

    @PutMapping
    public Result<String> update(@RequestBody Category category,HttpServletRequest request){

/*        LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();

        categoryWrapper.eq(!StringUtils.isEmpty(category),Category::getId,category.getId());*/

        categoryService.updateById(category);

        return Result.success("修改成功");
    }

    @DeleteMapping
    public Result<String> delete(Long id){

        //categoryService.removeById(id);

      return   categoryService.remove(id);
    }

    @GetMapping("/list")
    public Result<List<Category>> list(Integer type){

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(type!=null,Category::getType,type);

        List<Category> list = categoryService.list(wrapper);

        return Result.success(list);

    }

}
